package com.yuanqiworld.vw.web;

import com.yuanqiworld.vw.domain.Metadata;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RequestMapping("/metadatas")
@Controller
@RooWebScaffold(path = "metadatas", formBackingObject = Metadata.class)
@RooWebJson(jsonObject = Metadata.class)
public class MetadataController {

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Metadata metadata, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        Metadata old = Metadata.findMetadata(metadata.getId());
        if (!old.isRevisable()) {
            uiModel.asMap().clear();
            uiModel.addAttribute("error", "error.metadata.cannot.modified");
            return "redirect:/metadatas/" + encodeUrlPathSegment(metadata.getId().toString(), httpServletRequest);
        }
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, metadata);
            return "metadatas/update";
        }
        metadata.merge();
        uiModel.asMap().clear();
        return "redirect:/metadatas/" + encodeUrlPathSegment(metadata.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel, HttpServletRequest httpServletRequest) {
        Metadata metadata = Metadata.findMetadata(id);
        if (!metadata.isRevisable()) {
            uiModel.asMap().clear();
            uiModel.addAttribute("error", "error.metadata.cannot.delete");
            return "redirect:/metadatas/" + encodeUrlPathSegment(metadata.getId().toString(), httpServletRequest);
        }
        metadata.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/metadatas";
    }
}
